from maix import image, camera, display

cam = camera.Camera(320, 240)
disp = display.Display()

thresholds = [[0, 19, -10, 10, -12, 8],[0,18,-7,13,-21,-1],[8,28,-6,14,-24,-4]]

def line_feature(temp):#求直线k,b
    if temp[2] - temp[0] == 0: #防止分母为0
        k =0
    else:
        k = (temp[3] - temp[1]) / (temp[2] - temp[0])
    b = temp[1] - k * temp[0]
    return (k,b)

while 1:
    img = cam.read()
    objsholds = [thresholds[0]]

    blob1s = img.find_blobs(objsholds, area_threshold=500,pixels_threshold=10,roi=[0,0,320,60],merge=True)
    for blob1 in blob1s:
        img.draw_rect(blob1[0], blob1[1], blob1[2], blob1[3], image.COLOR_RED)#框
        cx1,cy1 = int(blob1[0]+blob1[2]/2),int(blob1[1]+blob1[3]/2)
        img.draw_cross(cx1, cy1, image.Color.from_rgb(0, 255, 0), size=5, thickness=2)

        blob2s = img.find_blobs(objsholds, area_threshold=500,pixels_threshold=10,roi=[0,60,320,60],merge=True)
        for blob2 in blob2s:
            img.draw_rect(blob2[0], blob2[1], blob2[2], blob2[3], image.COLOR_RED)#框
            cx2,cy2 = int(blob2[0]+blob2[2]/2),int(blob2[1]+blob2[3]/2)
            img.draw_cross(cx2, cy2, image.Color.from_rgb(0, 255, 0), size=5, thickness=2)

            blob3s = img.find_blobs(objsholds, area_threshold=500,pixels_threshold=10,roi=[0,120,320,60],merge=True)
            for blob3 in blob3s:
                img.draw_rect(blob3[0], blob3[1], blob3[2], blob3[3], image.COLOR_RED)#框
                cx3,cy3 = int(blob3[0]+blob3[2]/2),int(blob3[1]+blob3[3]/2)
                img.draw_cross(cx3, cy3, image.Color.from_rgb(0, 255, 0), size=5, thickness=2)

                img.draw_line(cx1,cy1,cx2,cy2, image.Color.from_rgb(255, 0, 0),thickness=5)
                img.draw_line(cx2,cy2,cx3,cy3, image.Color.from_rgb(255, 0, 0),thickness=5)
                img.draw_line(cx1,cy1,cx3,cy3, image.Color.from_rgb(0, 255, 0),thickness=2)
                img.draw_string(0, 10, str(cx1), image.Color.from_rgb(255, 0, 0), scale=2)
                img.draw_string(0, 30, str(cx2), image.Color.from_rgb(255, 0, 0), scale=2)
                img.draw_string(0, 50, str(cx3), image.Color.from_rgb(255, 0, 0), scale=2)

                line = [blob1[0], blob1[1],blob3[0], blob3[1]]
                lk=line_feature(line)
                img.draw_string(0, 70, "K:"+str(format(lk[0],".1f")), image.Color.from_rgb(255, 0, 0), scale=2)
    disp.show(img)